declare @objId int, @indId int, @porc decimal, @query nvarchar(max),@nombre varchar(max)
declare qFrac Cursor for

	select object_id,index_id, avg_fragmentation_in_percent
	from sys.dm_db_index_physical_stats(DB_ID('adventureworks2012'),OBJECT_ID('person.person'),null,null,'detailed')

open qFrac
Fetch next from qFrac into @objId,@indId,@porc
while @@FETCH_STATUS = 0
begin


select @nombre = name from sys.indexes 
where index_id = @indId
and object_id = @objId

		if @porc >30
			begin
			  print N'alter index '+ @nombre+' on person.person rebuild'
			end
		else if @porc < 30
			begin
			 print N'alter index '+@nombre+' on person.person reorganice'
			end
		else
			begin
			 print N'El indice no esta fragmentado'
			end
 
fetch next from qFrac into @objId,@indId,@porc

end
close qFrac
Deallocate qFrac 
